package com.catjiu.office.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.catjiu.common.entity.Result;
import com.catjiu.office.entity.DocInfo;
import com.catjiu.office.service.OfficeService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Scanner;

/**
 * <br>类描述：
 * <br>author： lwl liuwanli_eamil@163.com	2020/8/26 18:23
 *
 * @ClassName OfficeController
 * @see #
 * @since {修改人、修改时间、修改事由}
 */
@RestController
@RequestMapping("office")
public class OfficeController {
    @Value("${doc.save.path.store}")
    private String upload_file_path;

    @Autowired
    OfficeService officeService;

    @ApiOperation("加载文档列表")
    @GetMapping("list")
    public Result<List<DocInfo>> listDoc(){
        List<DocInfo> docInfos= officeService.list();
        return Result.ok().content(docInfos);
    }


    @ApiOperation("新建文档")
    @ApiImplicitParam(name = "fileName",value = "文档名称",paramType = "query")
    @GetMapping("create")
    public Result create(String fileName) throws IOException {
        File f = new File(upload_file_path+"/"+fileName);
        f.deleteOnExit();
        f.createNewFile();
        return Result.ok();
    }

    @ApiOperation("删除文档")
    @ApiImplicitParam(name = "fileName",value = "文档名称",paramType = "query")
    @GetMapping("delete")
    public Result delete(String fileName){
        File f = new File(upload_file_path+"/"+fileName);
        f.deleteOnExit();
        return Result.ok();
    }

    @ApiOperation("加载文档基本信息")
    @ApiImplicitParam(name = "filename",value = "文档名称",paramType = "query",required = true)
    @GetMapping("info")
    public Result<DocInfo> loadDoc(String filename){
        return Result.ok().content(new DocInfo());
    }

    @ApiOperation("下载文档")
    @GetMapping("download")
    public void download(String fileName,HttpServletResponse response) throws IOException {
        response.setContentType("application/*");
        response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream fis = new FileInputStream(new File(fileName));
        int j = 0;
        byte[] buffer = new byte[1024];
        while((j = fis.read(buffer)) > 0){
            out.write(buffer, 0, j);
        }
        // 关闭流
        fis.close();
        if(out!=null){
            out.flush();
            out.close();
        }
    }
    @ApiOperation("上传文档")
    @RequestMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        JSONObject res = new JSONObject();
        String fileName = file.getOriginalFilename();
        File f = new File(upload_file_path+"/"+fileName);
        try {
            file.transferTo(f.getAbsoluteFile().toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    @ApiOperation("文档保存回调接口")
    @PostMapping("save")
    public JSONObject callback(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        try {
            String body = "";
            Scanner scanner = new Scanner(request.getInputStream());
            scanner.useDelimiter("\\A");
            body = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
            if (body.isEmpty())
            {
                result.put("msg","empty request.getInputStream");
            }
            JSONObject jsonObj = JSON.parseObject(body);
            int status = (Integer) jsonObj.get("status");
            int saved = 0;
            if(status == 2 || status == 3) //MustSave, Corrupted
            {
                String downloadUri = (String) jsonObj.get("url");
                try
                {
                    URL url = new URL(downloadUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();
                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    String path = request.getParameter("path");
                    File savedFile = new File(upload_file_path+"/"+path);
                    try (FileOutputStream out = new FileOutputStream(savedFile))
                    {
                        int read;
                        final byte[] bytes = new byte[1024];
                        while ((read = stream.read(bytes)) != -1)
                        {
                            out.write(bytes, 0, read);
                        }

                        out.flush();
                    }
                    connection.disconnect();
                }
                catch (Exception ex)
                {
                    saved = 1;
                    ex.printStackTrace();
                }
            }
            result.put("error",saved);
        } catch (IOException e) {
            result.put("error",-1);
        }
        return result;
    }
}
